const fs = require("fs");
const path = require("path");
const cheerio = require("cheerio"); // 用来操作和抓取网络数据

const randomLetterPlugin = () => {
  const letters = ["我猜你", "有什么事吗", "看到我了嘛"];

  // 随机字符
  const printRandomLetter = () => {
    const randomIndex = Math.floor(Math.random() * letters.length);
    const randomLetter = letters[randomIndex];
    console.log("Random letter: ", randomLetter);
  };

  const versionInfo = {
    version: new Date().getTime(),
    subName: "", // 子应用的名称
  };

  return {
    name: "random-letter-plugin",
    configureServer(server) {
      // 服务器启动时立即执行
      printRandomLetter();
    },

    transform(code, id) {
      //   if (id.endsWith("main.js")) {
      //     return `${code}\nif (typeof window !== 'undefined'){
      //         const letters = ['我猜你', '有什么事吗', '看到我了嘛'];
      //         const printRandomLetter = () => {
      //             const randomIndex = Math.floor(Math.random() * letters.length);
      //             const randomLetter = letters[randomIndex];
      //             return randomLetter
      //         };
      //         console.log('%c' + printRandomLetter(), 'color:#1e80ff;fontsize:20px;padding:8px;background:#fff');
      //     }`;
      //   }
      try {
        // const filePath = path.resolve(`./template/version.json`);
        // fs.writeFile(
        //   filePath,
        //   JSON.stringify({ version: versionInfo.version }),
        //   (err) => {
        //     if (err) {
        //       console.log("错误信息" + err);
        //     }
        //   }
        // );
        // const htmlPath = path.resolve("./index.html");
        // console.log(htmlPath);
        // const data = fs.readFileSync(htmlPath);
        // const $ = cheerio.load(data);
        // $("body").append(
        //   `<div id='${versionInfo.subName}versionTag' style='display: none'>${versionInfo.version}</div>`
        // );
        // fs.writeFile(htmlPath, $.html(), (err) => {
        //   if (err) {
        //     console.log("html文件", err);
        //   }
        // });
      } catch (err) {
        console.log(err);
      }
      return code;
    },
  };
};

module.exports = randomLetterPlugin;
